package cn.tianya.irock.bll;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.tianya.fw.service.ComponentClientService;
import cn.tianya.fw.service.ServiceFactory;
import cn.tianya.irock.data.model.UserEx;
import cn.tianya.irock.enums.SystemExceptionType;
import cn.tianya.irock.exceptions.SystemException;
import cn.tianya.tw.component.TwitterServicePrx;
import cn.tianya.user.component.UserServicePrx;

public class UsersEx {
	private static UserServicePrx use_proxy;
	private static TwitterServicePrx tw_proxy;
	
	static {		
		ComponentClientService client = null;
		
		client = ServiceFactory.newInstance("user_service").getComponentClientService();
		use_proxy = client.getProxy(UserServicePrx.class);
		
		client = ServiceFactory.newInstance("twitter_service").getComponentClientService();
		tw_proxy = client.getProxy(TwitterServicePrx.class);
	}
	
	public static int getUserIdByName(String name) {
		return use_proxy.getUserIdByName(name);
	}
	
	public static String getUserNameByUserId(int userId) {
		return getUser(userId).getUsername();
	}
	
	public static String getUserInfoJson(int userId) {
		return use_proxy.getInfoById(userId, "detail", "json");
	}
	
	public static String getUserInfoJson(String name) {
		return use_proxy.getInfoByName(name, "detail", "json");
	}
	
	public static UserEx getUser(String name) {
		String str = getUserInfoJson(name);
		return UserEx.parse(str);
	}
	
	public static UserEx getUser(int userId) {
		String str = getUserInfoJson(userId);
		return UserEx.parse(str);
	}
	
	public static List<Integer> getUserFriends(int userId, String username, String ipAddr) {
		String str = null;
		JSONObject json = null;
		JSONArray array = null;
		ArrayList<Integer> list = null;
		String param = null;
		
		param = "{\"method\":\"following.ice.selectall\",\"params\":{},\"header\":{\"isOnline\":1,\"userIP\":\""+ipAddr+"\",\"userId\":" + Integer.toString(userId) + ",\"userName\":\""+username+"\"}}";
		try {
			str = tw_proxy.doRequest(param);
			json = new JSONObject(str);
			if ("1".equals(json.getString("success"))) {
				json = (JSONObject)json.get("data");
				array = (JSONArray)json.get("friend");
				list = new ArrayList<Integer>();
				for(int idx=0; idx<array.length(); idx++) {
					list.add(array.getInt(idx));
				}
			}
		} catch (Exception ex) {
			throw new SystemException(SystemExceptionType.APIError, "tianya twitter api error" + ex.getMessage() + str);
		}
		
		return list;
	}
}
